package com.liu.users.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.liu.common.pojo.InfoEnum;
import com.liu.common.service.impl.BaseServiceImpl;
import com.liu.common.util.ConstatFinalUtil;
import com.liu.common.util.PageInfoUtil;
import com.liu.users.dao.IARegionDao;
import com.liu.users.dao.IAUsersDao;
import com.liu.users.pojo.ARegion;
import com.liu.users.pojo.AUsers;
import com.liu.users.pojo.AUsersEnum;
import com.liu.users.service.IUsersService;

/**
 * 用户模块Service的实现类
 * @author lby
 *
 */
@Service("usersService")
public class UsersServiceImpl extends BaseServiceImpl implements IUsersService
{
	/*装配Dao的接口*/
	@Autowired
	private IAUsersDao usersDao;
	@Autowired
	private IARegionDao regionDao;
	
	/*=================用户列表开始=========================================================*/
	@Override
	public JSONObject saveOneUsersService(AUsers users)
	{
		JSONObject resultJson = new JSONObject();
		
		/* 先根据邮箱查询一下,是否重复 */
		Map<String,Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("email", users.getEmail());
		AUsers usersDb = this.findOneUsersService(condMap);
		if(usersDb != null)
		{
			/* 用户邮箱已经存在 */
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_EMAIL_EXISTS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.getString(resultJson.getString(InfoEnum.VAR_CODE.getInfo())));
			return resultJson ;
		}
		
		/* 密码加密 */
		users.setPassword(this.encryptUtil.encodeStr(users.getPassword()));
		/* 启用 */
		users.setStatus(AUsersEnum.STATUS_ENABLED.getStatus());
		
		users.setCreateTime(new Date());
		users.setUpdateTime(new Date());
		users.setLastLoginTime(new Date());
		
		/* 调用dao方法 */
		int res = this.usersDao.saveOneDao(users);
		
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_ID.getInfo(), users.getId());
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public JSONObject updateOneUsersService(AUsers users,Map<String, Object> paramsMap)
	{
		/**
		 * 先更新数据库
		 * 先上传图片
		 */
		JSONObject resultJson = this.updateOneUsersService(users);
		//验证除了图片都更新成功了，图片不为空,不为空字符串
		if(resultJson.getInteger("code") == InfoEnum.INFO_SUCCESS.getCode() && paramsMap != null && 
				!paramsMap.isEmpty())
		{
			/* 上传图片了 */
			//从pojo中取值
			String souPath = users.getPhotoPath() ; 
			
			/* 文件上传 */
			InputStream is = (InputStream) paramsMap.get("is");
			String fileName = (String) paramsMap.get("fileName");
			
			/* 拼装路径,完成上传
			 * 真实路径
			 * 网络路径
			 * 相对路径
			 *  */
			String truePath = ConstatFinalUtil.SYSTEM_JSON.getString("file.truePath") ; 
			String relaPath = ConstatFinalUtil.SYSTEM_JSON.getString("rela.path");
			relaPath += "/users/" + this.dateUtil.dateToStr(new Date()) + "/" ;
			relaPath += UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
			
			/* 拼装我们的真实文件对象 */
			File trueFile = new File(truePath + relaPath);
			if(!trueFile.getParentFile().exists())
			{
				trueFile.getParentFile().mkdirs() ; 
			}
			try
			{
				FileOutputStream fos = new FileOutputStream(trueFile);
				/* 拷贝流 */
				if(this.ioUtil.copyFile(is, fos))
				{
					/* 拷贝成功,赶紧把相对路径存储到数据库中 */
					users.setPhotoPath(relaPath);
					/* 就是为了更新路径 */
					this.updateOneUsersService(users);
					/* 删除老照片 */
					File souFile = new File(truePath + souPath); 
					if(!souFile.delete())
					{
						ConstatFinalUtil.LOGGER.error("==删除文件失败了=;" + trueFile.getAbsolutePath());
					}
				}else
				{
					ConstatFinalUtil.LOGGER.error("==上传文件失败了=;" + trueFile.getAbsolutePath());
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		return resultJson;
	}

	@Override
	public JSONObject deleteBatchUsersService(Map<String, Object> condMap)
	{
JSONObject resultJson = new JSONObject();
		
		if(condMap != null && condMap.isEmpty())
		{
			ConstatFinalUtil.LOGGER.error("请输入查询条件:{}",condMap);
			return resultJson ; 
		}
		
		/* 调用dao方法 */
		int res = this.usersDao.deleteBatchDao(condMap);
		
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public AUsers findOneUsersService(Map<String, Object> condMap)
	{
		//condMap不等于空，不等于null.
		if(condMap != null && condMap.isEmpty())
		{
			ConstatFinalUtil.LOGGER.error("请输入查询条件:{}",condMap);
			return null ; 
		}
		return this.usersDao.findOneDao(condMap);
	}

	@Override
	public List<AUsers>findCondListUsersService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{	
		/* 专门处理%的问题 */
		if(condMap.get(InfoEnum.FINA_KEYWORD.getInfo()) != null && !"".equalsIgnoreCase(condMap.get(InfoEnum.FINA_KEYWORD.getInfo()) + ""))
		{
			condMap.put(InfoEnum.FINA_KEYWORD.getInfo(), "%" + condMap.get(InfoEnum.FINA_KEYWORD.getInfo()) + "%") ; 
		}
		
		if(pageInfoUtil != null )
		{
			/* 分页 */
			Page<AUsers> page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			/* 调用查询语句 */
			List<AUsers> list = this.usersDao.findCondListDao(condMap);
			/* 获取总条数 */
			long total = page.getTotal();
			pageInfoUtil.setTotalRecord(Long.valueOf(total).intValue());
			return list ; 
		}
		return this.usersDao.findCondListDao(condMap);
	}
	/*=================用户列表结束=========================================================*/
	/*=================地区列表开始=========================================================*/
	@Override
	public JSONObject saveOneRegionService(ARegion region)
	{
		JSONObject resultJson = new JSONObject();
		
		region.setCreateTime(new Date());
		region.setUpdateTime(new Date());
		
		
		/* 调用dao方法 */
		int res = this.regionDao.saveOneDao(region);
		
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_ID.getInfo(), region.getId());
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public JSONObject updateOneRegionService(ARegion region)
	{
		JSONObject resultJson = new JSONObject();
		
		region.setUpdateTime(new Date());
		
		/* 调用dao方法 */
		int res = this.regionDao.updateOneDao(region);
		
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_ID.getInfo(), region.getId());
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public JSONObject deleteBatchRegionService(Map<String, Object> condMap)
	{
JSONObject resultJson = new JSONObject();
		
		if(condMap != null && condMap.isEmpty())
		{
			ConstatFinalUtil.LOGGER.error("请输入查询条件:{}",condMap);
			return resultJson ; 
		}
		
		/* 调用dao方法 */
		int res = this.regionDao.deleteBatchDao(condMap);
		
		if(res > 0 )
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));
			
			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);
			
			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		}else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;
	}

	@Override
	public ARegion findOneRegionService(Map<String, Object> condMap)
	{
		//condMap不等于空，不等于null.
		if(condMap != null && condMap.isEmpty())
		{
			ConstatFinalUtil.LOGGER.error("请输入查询条件:{}",condMap);
			return null ; 
		}
		return this.regionDao.findOneDao(condMap);
	}

	@Override
	public List<ARegion>findCondListRegionService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{	
		/* 专门处理%的问题 */
		if(condMap.get(InfoEnum.FINA_KEYWORD.getInfo()) != null && !"".equalsIgnoreCase(condMap.get(InfoEnum.FINA_KEYWORD.getInfo()) + ""))
		{
			condMap.put(InfoEnum.FINA_KEYWORD.getInfo(), "%" + condMap.get(InfoEnum.FINA_KEYWORD.getInfo()) + "%") ; 
		}
		
		if(pageInfoUtil != null )
		{
			/* 分页 */
			Page<ARegion> page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			/* 调用查询语句 */
			List<ARegion> list = this.regionDao.findCondListDao(condMap);
			/* 获取总条数 */
			long total = page.getTotal();
			pageInfoUtil.setTotalRecord(Long.valueOf(total).intValue());
			return list ; 
		}
		return this.regionDao.findCondListDao(condMap);
	}
	/*=================地区列表结束=========================================================*/

	@Override
	public JSONObject updateOneUsersService(AUsers users)
	{
		JSONObject resultJson = new JSONObject();

		users.setUpdateTime(new Date());

		/* 调用dao方法 */
		int res = this.usersDao.updateOneDao(users);

		if (res > 0)
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_SUCCESS.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(),
					ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_SUCCESS.getCode())));

			JSONObject dataJson = new JSONObject();
			dataJson.put(InfoEnum.VAR_ID.getInfo(), users.getId());
			dataJson.put(InfoEnum.VAR_EFFECT.getInfo(), res);

			resultJson.put(InfoEnum.VAR_DATA.getInfo(), dataJson);
		} else
		{
			resultJson.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_FAILED.getCode());
			resultJson.put(InfoEnum.VAR_INFO.getInfo(),
					ConstatFinalUtil.INFO_JSON.get(String.valueOf(InfoEnum.INFO_FAILED.getCode())));
		}
		return resultJson;}

	


}
